<template>
  <div>
    <div style="height: 87vh;padding: 10px 0">
      <div class="header">
        <div>
          <el-select
            @change="selectCategoryChange"
            style="width: 230px"
            size="mini" v-model="selectCategory" clearable filterable placeholder="请筛选品类">
            <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <el-select
            style="margin-left: 10px;"
            size="mini"
            v-if="!this.isNull(selectCategory)"
            @change="dateCycleChange"
            v-model="selectDateCycle"
            clearable filterable
            placeholder="按数据周期(淘宝)显示数据">
            <el-option
              v-for="item in dateCycleOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>

          <el-input
            style="margin-left: 5px; width: 150px;"
            placeholder="请输入搜索人数"
            v-show="tableShow"
            v-model="searchNum"
            size="mini"
            oninput="value=value.replace(/\D/g, '')"
            maxlength="10"
            clearable
            @clear="clearSearchNum">
          </el-input>
          <el-button style="margin-left: 5px;"
                     v-show="tableShow"
                     type="primary"
                     size="mini"
                     @click="getTableData"
          >
            筛选
          </el-button>

        </div>
        <div style="margin: 10px 0">
          <el-popconfirm
            title="是否将此关键词以不能包含的字符添加到过滤面板中？"
            style="margin-right: 5px"
            @confirm="delTableSelect(true)"
            @cancel="delTableSelect(false)"
          >
            <el-button
              slot="reference"
              v-show="tableData.length > 0"
              :disabled="selectTableData.length === 0"
              type="danger"
              size="mini"
            >
              移除选中项
            </el-button>
          </el-popconfirm>

          <el-popover
            v-if="tableShow"
            @show="showMarkEdit"
            style="margin-right: 5px"
            placement="bottom"
            width="250"
            trigger="click">
            <div style="text-align: center">
              <el-switch
                style="margin-bottom: 10px"
                v-model="isOpenUsage"
                active-text="标记"
                inactive-text="取消标记">
              </el-switch>

              <el-checkbox-group style="margin-bottom: 10px" v-model="selectUsageRecordList">
                <el-checkbox label="直通车"></el-checkbox>
                <el-checkbox label="标题"></el-checkbox>
                <el-checkbox label="补单"></el-checkbox>
              </el-checkbox-group>

              <el-select
                style="margin:10px 0"
                size="mini"
                v-model="group.selectId" filterable placeholder="请选择分组">
                <el-option
                  v-for="item in group.options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>

              <el-button
                type="primary"
                size="mini"
                style="width: 99%;font-weight: bold;font-size: 15px"
                @click="batchCommitUsageRecord"
              >
                提交
              </el-button>
            </div>


            <el-button
              slot="reference"
              :loading="tableLoading"
              v-show="tableShow"
              :disabled="selectTableData.length === 0"
              type="success"
              size="mini"
            >
              对选中项编辑用途
            </el-button>
          </el-popover>

          <copy-key-word-btn
            :select-row="selectTableData"
            :show="tableShow"
          >
          </copy-key-word-btn>

          <select-column
            style="margin-right: 5px"
            v-if="tableShow"
            :tb-ref-name="'virtualTb'"
            :tableShow="showTable"
            :defaultActivateColumns="checkedColumns"
            :tableDataProvider="tableDataProvider"
            @toRender="toRender"
          >
          </select-column>

          <key-word-group
            :show="tableShow"
            :loading="tableLoading"
          >
          </key-word-group>

          <view-record
            :provide-data-func="getViewData"
            :load-data-func="loadViewData"
            style="margin-right: 5px"
            v-if="tableShow"
          />
          <key-word-brand-character v-show="tableShow" />
          <el-button
            style="margin-left: 5px"
            :loading="tableLoading"
            v-show="tableShow"
            type="primary"
            size="mini"
            @click="filterShow=true"
          >
            过滤面板
          </el-button>

          <!--            v-show="filterParam.step === 2"-->
          <el-button
            v-if="false"
            type="primary"
            size="mini"
            @click="autoShow=true"
          >
            自动化面板
          </el-button>


          <!--          v-show="filterParam.step === 2"-->
          <el-popconfirm
            v-if="false"
            style="margin-left: 10px;"
            title="要以当前表格数据生成补单周期吗？"
            @confirm="builderOrderPlan"
          >

            <el-button
              slot="reference"
              :loading="tableLoading"
              type="primary"
              size="mini"
            >
              <el-tooltip effect="dark" content="分布订单天数" placement="top-start">
                <el-input-number size="mini" v-model="builderOrderDay" :min=1 :max=90></el-input-number>
              </el-tooltip>

              生成补单周期
            </el-button>
          </el-popconfirm>
        </div>
      </div>

      <div class="main">
        <div v-if="tableShow">
          <u-table
            ref="virtualTb"
            @selection-change="tableSelectChange"
            v-loading="tableLoading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            use-virtual
            showBodyOverflow="title"
            showHeaderOverflow="title"
            style="width: 100%"
            :height="679"
            :row-height="41"
            border
            :cell-style="{padding:'0px'}"
            :data="currentPageData"
            @sort-change="tableSortChange"
          >
            <u-table-column fixed="left" type="selection" width="40" />
            <u-table-column :show-overflow-tooltip=true fixed="left" prop="name" v-if="showTable.name" label="关键词"
                            width="200" />
            <u-table-column prop="categoryName" v-if="showTable.categoryName" label="品类" width="100" />
            <u-table-column prop="cycle" v-if="showTable.cycle" label="数据周期" width="200" />
            <u-table-column prop="searchPeopleNum" v-if="showTable.searchPeopleNum" sortable label="搜索人数"
                            width="110" />
            <u-table-column prop="searchCount" v-if="showTable.searchCount" sortable label="搜索次数" width="110" />
            <u-table-column prop="clickRate" v-if="showTable.clickRate" sortable label="点击率" width="100"
                            :formatter="valueToPercentage" />
            <u-table-column prop="clickPeopleNum" v-if="showTable.clickPeopleNum" sortable label="点击人数"
                            width="110" />
            <u-table-column prop="clickCount" v-if="showTable.clickCount" sortable label="点击次数" width="110" />
            <u-table-column prop="transactionAmount" v-if="showTable.transactionAmount" sortable label="交易金额"
                            width="110"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="paymentConversionRate" v-if="showTable.paymentConversionRate" sortable label="ROI"
                            width="110"
                            :formatter="valueToPercentage" />
            <u-table-column prop="onlineGoodsNum" v-if="showTable.onlineGoodsNum" sortable label="在线商品数"
                            width="120" />
            <u-table-column prop="mallClickRate" v-if="showTable.mallClickRate" sortable label="商城点击比例"
                            width="130"
                            :formatter="valueToPercentage" />
            <u-table-column prop="ztcReferencePrice" v-if="showTable.ztcReferencePrice" sortable label="直通车参考价"
                            width="130"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="paymentPeopleNum" v-if="showTable.paymentPeopleNum" sortable label="支付人数"
                            width="110" />
            <u-table-column prop="unitPrice" v-if="showTable.unitPrice" sortable label="客单价" width="100"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="searchUsersPerGoods" v-if="showTable.searchUsersPerGoods" sortable
                            label="搜索人数/在线商品数" width="180"
                            :formatter="percentageWithFixedDigits4" />
            <u-table-column prop="transactionAmountPerGoods" v-if="showTable.transactionAmountPerGoods" sortable
                            label="交易金额/在线商品数" width="180"
                            :formatter="percentageWithFixedDigits4" />
            <u-table-column prop="visitorAverageValue" v-if="showTable.visitorAverageValue" sortable
                            label="访客平均价值" width="130"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="goodsAverageValue" v-if="showTable.goodsAverageValue" sortable label="商品平均价值"
                            width="130"
                            :formatter="percentageWithFixedDigits4" />
            <u-table-column prop="visitorCompetitionIndex" v-if="showTable.visitorCompetitionIndex"
                            label="商品访客竞争度" width="120"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="highQualityValueWords" v-if="showTable.highQualityValueWords" sortable
                            label="优质价值词" width="120" />
            <u-table-column prop="competitionDegree" v-if="showTable.competitionDegree" sortable label="竞争度"
                            width="120"
                            :formatter="percentageWithFixedDigits4" />
            <u-table-column prop="estimatedConversionQuantity" v-if="showTable.estimatedConversionQuantity" sortable
                            label="预估转化件数" width="130"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="averageTransactionIndex" v-if="showTable.averageTransactionIndex" sortable
                            label="平均交易指数" width="130"
                            :formatter="percentageWithFixedDigits2" />
            <u-table-column prop="createdTime" v-if="showTable.createdTime" sortable label="创建时间" width="130" />

            <u-table-column align="center" label="直" width="35">
              <template slot-scope="{row}">
                <em
                  style="font-weight: bold;"
                  :class="row.isAppendZtc? 'el-icon-check' : 'el-icon-close'"
                  :style="row.isAppendZtc? {color: '#2ed573'} : {color: '#ff4757'}"
                  @click="usageRecordChange(row,'isAppendZtc')"
                ></em>
              </template>
            </u-table-column>
            <u-table-column align="center" label="标" width="35">
              <template slot-scope="{row}">
                <em
                  style="font-weight: bold;"
                  :class="row.isGenerateTitle? 'el-icon-check' : 'el-icon-close'"
                  :style="row.isGenerateTitle? {color: '#2ed573'} : {color: '#ff4757'}"
                  @click="usageRecordChange(row,'isGenerateTitle')"
                ></em>
              </template>
            </u-table-column>
            <u-table-column align="center" label="单" width="35">
              <template slot-scope="{row}">
                <em
                  style="font-weight: bold;"
                  :class="row.isGenerateOrderPlan? 'el-icon-check' : 'el-icon-close'"
                  :style="row.isGenerateOrderPlan? {color: '#2ed573'} : {color: '#ff4757'}"
                  @click="usageRecordChange(row,'isGenerateOrderPlan')"
                ></em>
              </template>
            </u-table-column>

            <u-table-column label="操作" width="60">
              <template slot-scope="{$index,row}">
                <el-popconfirm
                  title="是否将此关键词以不能包含的字符添加到过滤面板中？"
                  @confirm="delTableRow(row,true)"
                  @cancel="delTableRow(row,false)"
                >
                  <el-button slot="reference" type="text">
                    <span style="color: red">移除</span>
                  </el-button>
                </el-popconfirm>

              </template>
            </u-table-column>
          </u-table>
        </div>
        <div v-else>
          <div style="text-align: center">
            <p style="font-size: 20px;font-weight: bold;color: #57606f">展示数据步骤 </p>
            <p class="empty_content">1. 选择您需要查看的品类</p>
            <p class="empty_content">2. 选择此品类的数据周期</p>
          </div>
        </div>

      </div>

      <div class="footer" v-if="tableShow">
        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,50,100, 200, 300,500,1000]"
            :page-size=pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=tableData.length>
          </el-pagination>
        </div>
        <div>
          <span class="label">当前数据量 : </span>
          <span style="font-weight: bold;margin-right: 10px">{{ tableData.length }}</span>
          <span class="label">选中数据量 : </span>
          <span style="font-weight: bold">{{ selectTableData.length }}</span>
        </div>
      </div>
    </div>

    <!-- 一些遮罩显示的元素-->
    <div>
      <el-drawer
        size="25%"
        :visible.sync="filterShow"
        direction="rtl"
        title="过滤面板"
        @open="filterTemplateOpen"
      >
        <div style="margin: 0 5px;">
          <div style="height: 87vh;overflow-y:scroll;">
            <div style="margin: 10px 0 ">
              <div style="margin: 5px 0 " v-if="!this.isNull(filterParam.name)">
                <span>当前名称 : {{ filterParam.name }}</span>
              </div>
              <el-popover
                placement="left"
                width="80%"
                trigger="click">
                <el-table :data="filterTemplateList">
                  <el-table-column :show-overflow-tooltip="true" width="200" property="name"
                                   label="名称"></el-table-column>
                  <el-table-column sortable width="200" property="createTime" label="创建时间"></el-table-column>
                  <el-table-column sortable width="200" property="updateTime" label="修改时间"></el-table-column>
                  <el-table-column width="200" label="操作">
                    <template slot-scope="scope">
                      <el-button size="mini" type="primary" @click="loadFilterTemplate(scope.row)">加载</el-button>
                      <el-button size="mini" type="danger" @click="deleteFilterTemplate(scope.row.id)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button size="mini" type="primary" slot="reference">查看记录模板</el-button>
              </el-popover>
              <el-button style="margin-left: 10px" size="mini" type="primary" @click="commitFilterTemplate">
                提交当前面板
              </el-button>
              <el-popconfirm
                style="margin-left: 10px"
                confirm-button-text="确认"
                cancel-button-text="点错了"
                icon="el-icon-info"
                icon-color="red"
                title="恢复默认将刷新页面,确认吗？"
                @confirm="handleDefTemplate"
              >
                <el-button slot="reference" size="mini" type="primary">
                  恢复默认
                </el-button>
              </el-popconfirm>

            </div>
            <div style="margin: 0 15px;">
              <div style="margin-bottom: 30px">
                <el-steps :active="filterParam.step">
                  <el-step></el-step>
                  <el-step></el-step>
                  <el-step></el-step>
                </el-steps>
              </div>
              <div>
                <div v-if="filterParam.step === 0">
                  <div style="margin: 5px 0">
                    <span class="label">移除交易金额小于 : </span>
                    <el-input-number
                      v-model="filterParam.params[0].minAmount"
                      :precision=2
                      :min="0"
                      :max="1000000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <div style="margin: 5px 0">
                    <span class="label">移除支付人数小于 : </span>
                    <el-input-number
                      v-model="filterParam.params[0].minPaymentPeople"
                      :min="0"
                      :max="1000000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <div style="margin: 5px 0">
                    <span class="label">移除客单价小于 : </span>
                    <el-input-number
                      v-model="filterParam.params[0].minUnitPrice"
                      :precision=2
                      :min="0"
                      :max="1000000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <div style="margin: 5px 0">
                    <span class="label">移除客单价大于 : </span>
                    <el-input-number
                      style="width: 150px"
                      v-model="filterParam.params[0].maxUnitPrice"
                      :precision=2
                      :min=filterParam.params[0].minUnitPrice
                      :max="1000000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <div style="margin: 5px 0">
                    <span class="label">移除访客平均价值小于 : </span>
                    <el-input-number
                      v-model="filterParam.params[0].minVisitorAverageValue"
                      :precision=2
                      :min="0"
                      :max="1000000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                </div>
                <div v-if="filterParam.step === 1">
                  <div style="margin: 5px 0">
                    <span class="label">保留按搜索人数倒叙前百分比 : </span>
                    <el-input-number
                      v-model="filterParam.params[1].searchPeopleNumPer"
                      :min="1"
                      :precision=2
                      :max="100"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <div style="margin: 5px 0">
                    <span class="label">保留按交易金额倒叙前百分比 : </span>
                    <el-input-number
                      v-model="filterParam.params[1].amountPer"
                      :precision=2
                      :min="1"
                      :max="100"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                  <el-divider content-position="center">注:已保留的数据不会被移除</el-divider>
                  <div style="margin: 5px 0">
                    <span class="label">移除搜索人数/在线商品数值小于 : </span>
                    <el-input-number
                      v-model="filterParam.params[1].minSearchUsersPerGoods"
                      :precision=2
                      :min="0"
                      :max="1000"
                      size="small"
                    >
                    </el-input-number>
                  </div>
                </div>
                <div v-if="filterParam.step === 2">
                  <div style="margin: 5px 0">
                    <span class="label">移除关键词长度大于 : </span>
                    <el-input-number
                      v-model="filterParam.params[2].keyWordMaxLength"
                      :min="0"
                      :max="100"
                      size="small"
                    >
                    </el-input-number>
                  </div>

                  <div style="margin: 5px 0">
                    <span class="label" style="margin-right: 20px;"></span>
                    <el-button size="small" @click="addIncludeText">添加关键词必须包含的字符</el-button>
                    <div style="margin: 5px 0">
                      <el-tag
                        style="margin: 0 5px"
                        v-for="(tag,index) in filterParam.params[2].includeText"
                        :key="index"
                        closable
                        @close="filterParam.params[2].includeText.splice(index,1)"
                        type="info">
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>

                  <div style="margin: 5px 0">
                    <span class="label" style="margin-right: 20px;"></span>
                    <el-button size="small" @click="addNotIncludeText">添加关键词不能包含的字符</el-button>
                    <div style="margin: 5px 0">
                      <el-tag
                        style="margin: 0 5px 5px 0"
                        v-for="(tag,index) in filterParam.params[2].notIncludeText"
                        :key="index"
                        closable
                        @close="filterParam.params[2].notIncludeText.splice(index,1)"
                        type="info">
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>

                  <div style="margin: 5px 0">
                    <span class="label">移除包含品牌的关键词 : </span>
                    <el-switch
                      @change="notIncludeBrandWordChange"
                      v-model="filterParam.params[2].notIncludeBrandWord"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </div>

                  <div style="margin: 5px 0">
                    <span class="label">移除包含英文字母的关键词 : </span>
                    <el-switch
                      v-model="filterParam.params[2].notIncludeEnglish"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div style="display: flex;justify-content: space-between;">
            <el-button :disabled="filterParam.step === 0" type="success" @click="filterPrevious()">上一步</el-button>
            <el-button :disabled="filterParam.step >= 2" type="info" @click="skipFilter">跳过</el-button>
            <el-button :disabled="filterParam.step >= 3" type="primary" @click="filterNext(false)">
              {{ filterParam.step >= 2 ? "已完成" : "下一步" }}
            </el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
/*是否模拟请求并返回参数
* cmd : json-server --watch src/views/manage/keyWord/mockData.json --port 3001
* */
import { formatPercentage, isNull, daysBetween, globalLoading } from "@/utils/service";
import msg from "@/utils/message";
import brandWord, {
  commitUsageRecord, getCategoryOptions
} from "@/views/manage/keyWord/api/index.js";
import { list as filterList, commit as filterCommit, remove as filterRemove } from "@/api/operationaid/filterTemplate";
import { getOptions as getGroupOptions } from "@/views/manage/keyWord/component/groupApi.js";
import { batchCommitUsageRecord } from "./api/index";
import CopyKeyWordBtn from "@/views/manage/keyWord/component/copyKeyWordBtn.vue";
import KeyWordGroup from "@/views/manage/keyWord/component/keyWordGroup.vue";
import ViewRecord from "@/views/public/viewRecord.vue";
import SelectColumn from "@/components/utils/SelectColumn.vue";
import keyWordBrandCharacter from "@/views/manage/keyWord/component/keyWordBrandCharacter.vue";

const mock = false;
export default {
  name: "index",
  components: { ViewRecord, KeyWordGroup, CopyKeyWordBtn, SelectColumn, keyWordBrandCharacter },
  computed: {
    currentPageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
  },
  created() {
    // 初始化 checkedColumns 且将 tableShow 对象的每个属性为布尔值且默认为 true
    const initialProperties =
      [
        "name", "categoryName", "cycle", "searchPeopleNum", "searchCount", "clickRate", "clickPeopleNum", "clickCount",
        "transactionAmount", "paymentConversionRate", "onlineGoodsNum", "mallClickRate", "ztcReferencePrice",
        "paymentPeopleNum", "unitPrice", "searchUsersPerGoods", "transactionAmountPerGoods", "visitorAverageValue",
        "goodsAverageValue", "visitorCompetitionIndex", "highQualityValueWords", "competitionDegree", "estimatedConversionQuantity",
        "averageTransactionIndex", "createdTime"
      ];
    this.showTable = Object.fromEntries(initialProperties.map(property => [property, true]));
    this.checkedColumns = initialProperties;
  },
  mounted() {
    this.getCategoryOptions();
  },
  data() {
    return {
      isOpenUsage: true,
      /** 选中的用途记录列表*/
      selectUsageRecordList: [],
      headerRowStyle: {
        "background-color": "#57606f"
      },
      /** 选中的数据周期*/
      selectDateCycle: undefined,
      dateCycleOptions: [],
      categoryOptions: [],
      /** 选中的品类*/
      selectCategory: "",
      searchNum: undefined,
      tableShow: false,
      tableData: [],
      showTable: {},
      checkedColumns: [],
      currentPage: 1,
      /** 单页条目数*/
      pageSize: 100,
      pageSizeOptions: [
        30,
        50,
        100,
        200,
        300
      ],
      selectTableData: [],
      tableLoading: true,
      filterTemplateList: [],
      filterShow: false,
      /** 过滤模板参数*/
      filterParam: {
        id: undefined,
        name: "",
        step: 0,
        params: [
          {
            isActive: true,
            /*交易金额最小值*/
            minAmount: 500,
            /*支付人数最小值*/
            minPaymentPeople: 3,
            /*客单价最小值*/
            minUnitPrice: 100,
            /*客单价最大值*/
            maxUnitPrice: 99999,
            /*访客平均价值最小值*/
            minVisitorAverageValue: 3,
            beforeTableData: [],
            baseData: []
          },
          {
            isActive: true,
            /*搜索人数前百分比保留*/
            searchPeopleNumPer: 50,
            /*交易金额前百分比保留*/
            amountPer: 50,
            /*搜索人数/在线商品数 最小值*/
            minSearchUsersPerGoods: 1,
            beforeTableData: [],
            baseData: []
          },
          {
            isActive: true,
            /*关键词最大长度*/
            keyWordMaxLength: 28,
            /*包含指定关键词的保留*/
            includeText: [],
            /*不包含指定关键词的保留*/
            notIncludeText: [],
            beforeTableData: [],
            baseData: [],
            /* 不包含品牌词 */
            notIncludeBrandWord: false,
            /* 不包含英文字母 */
            notIncludeEnglish: false
          }
        ]
      },
      /*分组选项*/
      group: {
        options: [],
        selectId: 0
      }
    };
  },
  methods: {
    tableDataProvider() {
      return JSON.parse(JSON.stringify(this.tableData));
    },
    toRender(componentData) {
      if (componentData.tableList) {
        this.tableData = componentData.tableList;
      }
    },
    defGroupOptions() {
      let _ = this;
      _.group.selectId = 0;
      getGroupOptions(this, this.selectCategory, r => {
        _.group.options = r;
      }, f => {
      });
    },
    showMarkEdit() {
      this.defGroupOptions();
    },
    handleSizeChange(v) {
      this.pageSize = v;
    },
    handleCurrentChange(v) {
      this.currentPage = v;
    },
    usageRecordChange(row, field) {
      row[field] = !row[field];
      commitUsageRecord(this, row);
    },
    /** 数据周期改变监听*/
    dateCycleChange(v) {
      if (this.isNull(v)) {
        this.tableShow = false;
        this.tableData = [];
        this.selectTableData = [];
        this.defFilterTemplate();
        return;
      }
      this.tableShow = true;
      this.getTableData();
    },
    /** 品类选择改变监听*/
    selectCategoryChange(v) {
      this.selectDateCycle = "";
      this.defGroupOptions();
      if (this.isNull(v)) {
        this.selectCategory = "";
        this.tableShow = false;
        this.tableData = [];
        this.selectTableData = [];
        this.defFilterTemplate();
        return;
      }
      this.getDateCycleOptions();
    },
    /** 表格选中改变*/
    tableSelectChange(v) {
      this.selectTableData = v;
    },
    /** 移除表格选中项*/
    delTableSelect(isAppendNotIncludesText) {
      if (this.selectTableData.length === 0) {
        this.$message.warning("没有选中任何数据");
        return;
      }
      let _ = this;
      _.tableData = _.tableData.filter((item) => {
        if (!_.selectTableData.includes(item)) {
          return true;
        } else {
          if (isAppendNotIncludesText) {
            this.filterParam.params[2].notIncludeText.push(item.name);
          }
        }
      });
    },
    /** 移除指定行*/
    delTableRow(row, isAddToFilter) {
      if (isAddToFilter) {
        this.filterParam.params[2].notIncludeText.push(row.name);
      }
      let index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    skipFilter() {
      let step = this.filterParam.step;
      this.filterParam.params[step].isActive = true;
      this.filterParam.params[step].beforeTableData = this.tableData;
      this.filterParam.step++;
    },
    /** 过滤面板下一步 */
    filterNext() {
      let step = this.filterParam.step;
      if (this.filterParam.step > 2) {
        return;
      }
      this.filterParam.params[step].beforeTableData = this.tableData;
      if (isNull(this.filterParam.params[step].baseData)) {
        this.filterParam.params[step].baseData = this.tableData;
      }
      if (step === 0) {
        this.tableData = this.filterStep1();
      } else if (step === 1) {
        this.tableData = this.filterStep2();
      } else if (step === 2) {
        this.tableData = this.filterStep3();
        this.filterShow = false;
        return;
      }
      this.filterParam.step++;
    },
    filterStep1() {
      let f = this.filterParam.params[0];
      if (!f.isActive) {
        return this.tableData;
      }
      return f.baseData.filter(item => {
        return item.transactionAmount >= f.minAmount && item.paymentPeopleNum >= f.minPaymentPeople
          && item.unitPrice >= f.minUnitPrice && item.unitPrice <= f.maxUnitPrice && item.visitorAverageValue >= f.minVisitorAverageValue;
      });
    },
    filterStep2() {
      let _ = this;
      let now = this.filterParam.params[1];
      let baseData = now.baseData;
      if (!now.isActive) {
        return this.tableData;
      }
      // 搜索人数保留
      let reserveData = [];
      baseData.sort((a, b) => b.searchPeopleNum - a.searchPeopleNum);
      let reserveLength = Math.ceil(baseData.length * (now.searchPeopleNumPer / 100));
      reserveData = reserveData.concat(baseData.slice(0, reserveLength));
      // 交易金额保留
      baseData.sort((a, b) => b.transactionAmount - a.transactionAmount);
      reserveLength = Math.ceil(this.tableData.length * (now.amountPer / 100));
      reserveData = [...new Set([...reserveData, ...baseData.slice(0, reserveLength)])];
      // 获取需要过滤的数据
      let fData = baseData.filter(item => !reserveData.includes(item))
        // 过滤
        .filter(item => item.searchUsersPerGoods >= now.minSearchUsersPerGoods);
      // 将需要保留的数据再次拼接返回
      return reserveData.concat(fData);
    },
    filterStep3() {
      let _ = this;
      let now = _.filterParam.params[2];
      let baseData = now.baseData;
      if (!now.isActive) {
        return this.tableData;
      }
      let reserveData = [];
      reserveData = baseData.filter(item => item.name.length <= now.keyWordMaxLength);
      if (now.includeText.length > 0) {
        reserveData = reserveData.filter(item => now.includeText.every(t => item.name.includes(t)));
      }
      if (now.notIncludeText.length > 0) {
        reserveData = reserveData.filter(item => now.notIncludeText.every(t => !item.name.includes(t)));
      }
      if (now.notIncludeEnglish) {
        reserveData = reserveData.filter(item => !/[a-zA-Z]/.test(item.name));
      }
      return reserveData;
    },
    /** 过滤面板上一步 */
    filterPrevious() {
      if (this.filterParam.step === 0) {
        return;
      }
      this.filterParam.step--;
      this.tableData = this.filterParam.params[this.filterParam.step].beforeTableData;
      this.filterParam.params[this.filterParam.step].beforeTableData = [];
    },
    /**  添加包含字符*/
    addIncludeText() {
      let _t = this;
      this.$prompt("添加关键词必须包含的字符", "添加字符", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "支持一次输入多个例如:(平底锅,炒锅)"
      }).then(({ value }) => {
        if (isNull(value)) {
          return;
        }
        let newList = value.split(/[,，]/)
          .map(item => item.trim())
          .filter(item => item !== "");
        let hasIntersection = _t.filterParam.params[2].includeText.concat(_t.filterParam.params[2].includeText).some(old => {
          old = old.toString();
          return newList.some(newStr => newStr === old || newStr.includes(old));
        });
        if (hasIntersection) {
          msg.warning("新增的字符已经存在");
          return;
        }
        _t.filterParam.params[2].includeText = [
          ...new Set(_t.filterParam.params[2].includeText.concat(newList))
        ];
      }).catch((err) => {
        console.log(err);
      });
    },
    /**  添加不能包含的字符*/
    addNotIncludeText() {
      let _t = this;
      this.$prompt("添加关键词不能包含的字符", "添加字符", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "支持一次输入多个例如:(平底锅,炒锅)"
      }).then(({ value }) => {
        if (isNull(value)) {
          return;
        }
        let newList = value.split(/[,，]/)
          .map(item => item.trim())
          .filter(item => item !== "");
        let hasIntersection = _t.filterParam.params[2].notIncludeText.concat(_t.filterParam.params[2].notIncludeText).some(old => {
          old = old.toString();
          return newList.some(newStr => newStr === old || newStr.includes(old));
        });
        if (hasIntersection) {
          msg.warning("新增的字符已经存在");
          return;
        }
        _t.filterParam.params[2].notIncludeText = [
          ...new Set(_t.filterParam.params[2].notIncludeText.concat(newList))
        ];
      }).catch((err) => {
        console.log(err);
      });
    },
    /** 移除不包含品牌关键词选项改变监听 */
    notIncludeBrandWordChange(v) {
      if (v) {
        this.filterParam.params[2].notIncludeText = [...new Set([...this.filterParam.params[2].notIncludeText, ...brandWord])];
      } else {
        this.filterParam.params[2].notIncludeText = this.filterParam.params[2].notIncludeText.filter(item => !brandWord.includes(item));
      }
    },
    filterTemplateOpen() {
      this.getFilterTemplateList();
    },
    getCategoryOptions() {
      getCategoryOptions(this, "categoryOptions");
    },
    /** 获取数据周期选项*/
    getDateCycleOptions() {
      let _t = this;
      this.$request.post({
        url: "operationAid/KeyWord/cycleList",
        params: {
          categoryName: _t.selectCategory
        },
        success: res => {
          _t.dateCycleOptions = res;
        },
        error: err => {
          console.log(err);
          _t.message.warning("获取数据周期选项失败");
        }
      });

    },
    tableSortChange(column, prop, order) {
      if (!isNull(column.order)) {
        if (column.order.startsWith("asc")) {
          this.tableData.sort((a, b) => a[column.prop] - b[column.prop]);
        } else {
          this.tableData.sort((a, b) => b[column.prop] - a[column.prop]);
        }
      } else {
        this.tableData.sort((a, b) => b["searchPeopleNum"] - a["searchPeopleNum"]);
      }
    },
    /** 获取表格数据*/
    getTableData() {
      let _t = this;
      _t.tableLoading = true;
      this.$request.post({
        url: "operationAid/KeyWord/table",
        params: {
          cycle: _t.selectDateCycle,
          categoryName: _t.selectCategory,
          searchPeopleNum: _t.searchNum
        },
        success: res => {
          _t.tableData = res;
          // 重载过滤
          let nowFilterStep = _t.filterParam.step;
          if (nowFilterStep === 0) {
            return;
          }
          // 当前过滤步骤大于 1 才需要过滤
          for (let i = 0; i <= nowFilterStep; i++) {
            // 将当前步骤至于当前步骤的上一步 然后下一步方法
            _t.filterParam.step = i;
            _t.filterParam.params[i].baseData = [];
            _t.filterNext();
          }
        },
        error: err => {
          console.log(err);
          _t.message.warning("获取表格数据失败");
        },
        allError: err => {
          console.log(err);
        },
        finally: res => {
          _t.tableLoading = false;
        }
      });
    },
    /** 重置搜索人数并恢复默认列表 */
    clearSearchNum() {
      let _ = this;
      _.searchNum = undefined;
      _.getTableData();
    },
    /** 获取过滤模板列表*/
    getFilterTemplateList() {
      let _ = this;
      filterList("GJC").then(r => {
        _.filterTemplateList = r;
      }).catch(err => {
        console.log(err);
      });
    },
    commitFilterTemplate() {
      let _ = this;
      // 去除不需要的字段
      let params = this.filterParam.params.map(({ beforeTableData, baseData, ...t }) => t);
      let p = {
        templateId: this.filterParam.id,
        templateName: this.filterParam.name,
        paramList: JSON.stringify(params),
        type: "GJC"
      };
      let inputDef = "";
      if (!isNull(p.templateId)) {
        inputDef = p.templateName;
      }
      this.$prompt("请输入新模板名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\s*[\S\s]+\s*$/,
        inputErrorMessage: "请填新模板名称",
        inputValue: inputDef
      }).then(({ value }) => {
        p.templateName = value;
        let loading = globalLoading(_);
        filterCommit(p).then(r => {
          _.$message.success("提交模板成功");
          _.getFilterTemplateList();
          _.filterParam.params.id = r;
          _.filterParam.name = p.templateName;
        }).finally(() => {
          loading.close();
        });
      });
    },
    handleDefTemplate() {
      this.defFilterTemplate();
      this.getTableData();
    },
    defFilterTemplate() {
      this.filterParam = {
        id: undefined,
        name: "",
        step: 0,
        params: [
          {
            isActive: true,
            /*交易金额最小值*/
            minAmount: 500,
            /*支付人数最小值*/
            minPaymentPeople: 3,
            /*客价最小值*/
            minUnitPrice: 100,
            /*客单价最大值*/
            maxUnitPrice: 99999,
            /*访客平均价值最小值*/
            minVisitorAverageValue: 3,
            beforeTableData: [],
            baseData: []
          },
          {
            isActive: true,
            /*搜索人数前百分比保留*/
            searchPeopleNumPer: 50,
            /*交易金额前百分比保留*/
            amountPer: 50,
            /*搜索人数/在线商品数 最小值*/
            minSearchUsersPerGoods: 1,
            beforeTableData: [],
            baseData: []
          },
          {
            isActive: true,
            /*关键词最大长度*/
            keyWordMaxLength: 28,
            /*包含指定关键词的保留*/
            includeText: [],
            /*不包含指定关键词的保留*/
            notIncludeText: [],
            beforeTableData: [],
            baseData: [],
            /* 不包含品牌词 */
            notIncludeBrandWord: false,
            /* 不包含英文字母 */
            notIncludeEnglish: false
          }
        ]
      };
    },
    deleteFilterTemplate(id) {
      let loading = globalLoading(this);
      filterRemove(id).then(r => {
        this.$message.success("删除成功")
        this.getFilterTemplateList()
      }).finally(() => {
        loading.close();
      });
    },
    loadFilterTemplate({ id, name, params }) {
      this.filterParam.step = 0;
      this.filterParam.id = id;
      this.filterParam.name = name;
      this.filterParam.params = JSON.parse(params);
      this.filterParam.params[0]["beforeTableData"] = [];
      this.filterParam.params[1]["beforeTableData"] = [];
      this.filterParam.params[2]["beforeTableData"] = [];
      this.filterParam.params[0]["baseData"] = [];
      this.filterParam.params[1]["baseData"] = [];
      this.filterParam.params[2]["baseData"] = [];
      this.getTableData();
    },
    batchCommitUsageRecord() {
      let isAppendZtc = this.selectUsageRecordList.includes("直通车");
      let isGenerateTitle = this.selectUsageRecordList.includes("标题");
      let isGenerateOrderPlan = this.selectUsageRecordList.includes("补单");
      batchCommitUsageRecord(this, this.selectTableData, this.isOpenUsage
        , isAppendZtc, isGenerateTitle, isGenerateOrderPlan, this.group.selectId);
    },
    /** 将表格值转为百分比*/
    valueToPercentage(row, column, cellValue, index) {
      return formatPercentage(cellValue);
    },
    /** 表格值保留两位小数*/
    percentageWithFixedDigits2(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(2) : "-";
    },
    /** 表格值保留三位小数*/
    percentageWithFixedDigits4(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(4) : "-";
    },
    getViewData() {
      return {
        selectCategory: this.selectCategory,
        selectDateCycle: this.selectDateCycle,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        filterParam: {
          id: this.filterParam.id,
          name: this.filterParam.name,
          step: this.filterParam.step,
          // 去除缓存数据的字段
          params: this.filterParam.params.map(({ beforeTableData, baseData, ...t }) => t)
        }
      };
    },
    loadViewData(param) {
      let loading = this.$loading({
        lock: true,
        text: "加载记录中.....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.selectCategory = param.selectCategory;
      this.selectDateCycle = param.selectDateCycle;
      this.currentPage = param.currentPage;
      this.pageSize = param.pageSize;
      // 对过滤模板参数进行赋值
      if (param.filterParam.id) {
        this.filterParam.id = param.filterParam.id;
        this.filterParam.name = param.filterParam.name;
      } else {
        this.filterParam.id = undefined;
        this.filterParam.name = "";
      }
      this.filterParam.step = param.filterParam.step;
      for (let i = 0; i < param.filterParam.params.length; i++) {
        this.filterParam.params[i] = param.filterParam.params[i];
        this.filterParam.params[i]["beforeTableData"] = [];
      }
      this.getTableData();
      loading.close();
    }
  }
};
</script>

<style scoped>
.empty_content {
  color: #636e72;
  font-size: 16px;
}

.label {
  color: #57606f;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 0.05em;
}

.header {
  margin: 10px 0 10px 0
}

.main {
  margin: 10px 0 10px 0
}

.footer {
  margin: 10px 0 10px 0;
  display: flex;
  justify-content: space-between;
}

/deep/ .el-empty__description p {
  font-size: 30px !important;
  font-weight: bold !important
}
</style>